package com.zhanglijie.improve.atomic.five;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/9/10 0010 15:22
 * 多线程测试
 */
public class TestAtomicArray2 {
    static AtomicIntegerArray atomicArray = new AtomicIntegerArray(10);
    static int[] safeArray = new int[10];
    static int[] noSafeArray = new int[10];

    public static void main(String[] args) throws InterruptedException {

        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                for (int i1 = 0; i1 < 10000; i1++) {
                    atomicArray.addAndGet(i1%atomicArray.length(),1);
                    synchronized (safeArray){
                        safeArray[i1%safeArray.length] += 1;
                    }
                    noSafeArray[i1%safeArray.length] += 1;
                }
                countDownLatch.countDown();
            }).start();
        }
        countDownLatch.await();
        System.out.println("atomicArray:");
        for (int i = 0; i < atomicArray.length(); i++) {
            System.out.print(atomicArray.get(i)+" ,");
        }

        System.out.println();
        System.out.println("safeArray:");
        for (int i = 0; i < safeArray.length; i++) {
            System.out.print(safeArray[i]+" ,");
        }

        System.out.println();
        System.out.println("noSafeArray:");
        for (int i = 0; i < noSafeArray.length; i++) {
            System.out.print(noSafeArray[i]+" ,");
        }

    }
}
